//
//  Face.m
//  ChampoinPeso
//
//  Created by mac on 2025/2/17.
//

#import "Face.h"
#import "FaceDetail.h"
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>
#import "PopTool.h"
#import "InfoVerify.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
#import "FaceType.h"
#import "LocationUpdata.h"
#import <SDWebImage/SDWebImage.h>
@interface Face ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextFieldDelegate>
@property (nonatomic,strong)UIButton *apply;
@property (nonatomic,strong)NSDictionary *faceInfo;
@property (nonatomic,assign)BOOL onControl;
@property (nonatomic,assign)BOOL backControl;
@property (nonatomic,strong)NSDictionary *peso;
@property (nonatomic,strong)NSString *type;
@property (nonatomic,assign)BOOL typeChos;
@property (nonatomic,strong)NSString *photoType;
@property (nonatomic,strong)NSString *itemType;
@end

@implementation Face

//test.feilvbin.two
//ms.feilvbin.two

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = UIColor.whiteColor;
    self.navtitleText = @"ldentity information";
    [self navUI];
    self.typeChos = YES;
//    self.type = @"TIN";
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"typeCs"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    self.type = @"";
    [self moveReq];
}





- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    [IQKeyboardManager sharedManager].enable = NO;
//    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    NSString *typt = [[NSUserDefaults standardUserDefaults] objectForKey:@"typeCs"];
    if(![typt isEqualToString:@""]){
        self.type = typt;
    }
    
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
//    [IQKeyboardManager sharedManager].enable = YES;
//    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
}

- (void)moveReq {
    NSString *adjadjadj = [[NSUserDefaults standardUserDefaults] objectForKey:@"adjadjadj"];
    [DataFrameMove frameMoverForPost:@"/cham/consider" MoverPost:YES frameParm:@{@"gossip":adjadjadj} finish:^(id  _Nonnull info) {
        self.faceInfo = info[@"fashion"];
        if([info[@"fashion"][@"secretly"][@"perfect"] intValue] == 0){
            self.onControl = NO;
        } else {
            self.onControl = YES;
        }
        if([info[@"fashion"][@"killings"][@"perfect"] intValue] == 0){
            self.backControl = NO;
        } else {
            self.backControl = YES;
        }
        
        if(self.onControl == YES && self.backControl == YES){
            for (UIView *subV in self.view.subviews) {
                [subV removeFromSuperview];
            }
            [self finishUI];
            self.navtitleText = @"ldentity information";
            [self navUI];
        } else {
            for (UIView *subV in self.view.subviews) {
                [subV removeFromSuperview];
            }
            [self setupUI];
            self.navtitleText = @"ldentity information";
            [self navUI];
        }
    }];
}

- (void)finishUI {
    UIImageView *bgIv = [UIImageView new];
    [self.view addSubview:bgIv];
    bgIv.image = [UIImage imageNamed:@"face_over_top"];
    [bgIv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(STATUS_BAR_HEIGHT + 44);
        make.left.mas_offset(6);
        make.right.mas_offset(-6);
        make.height.mas_equalTo(33);
    }];
    
    UILabel *labon =[UILabel new];
    labon.text = @"Front of ID photo";
    labon.textColor = HexColor(@"#212121");
    labon.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    [self.view addSubview:labon];
    [labon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(bgIv.mas_bottom).mas_offset(44);
        make.height.mas_equalTo(18);
    }];
    labon.textAlignment = NSTextAlignmentCenter;
    
    
    UIImageView *imgOn = [UIImageView new];
    [self.view addSubview:imgOn];
    [imgOn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(labon.mas_bottom).mas_offset(22);
        make.height.mas_equalTo(132);
        make.width.mas_equalTo(221);
        make.centerX.equalTo(self.view);
    }];
    [imgOn sd_setImageWithURL:[NSURL URLWithString:self.faceInfo[@"secretly"][@"stop"]]];

    UIImageView *imgOnRight = [UIImageView new];
    [self.view addSubview:imgOnRight];
    [imgOnRight mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.width.mas_equalTo(66);
        make.bottom.equalTo(imgOn);
        make.right.equalTo(imgOn.mas_right).mas_offset(22);
    }];
    imgOnRight.image = [UIImage imageNamed:@"face_pic_ok"];
    
    UILabel *labUnder = [UILabel new];
    labUnder.text = @"Face recognition";
    labUnder.textColor = HexColor(@"#212121");
    labUnder.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    [self.view addSubview:labUnder];
    [labUnder mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(imgOn.mas_bottom).mas_offset(72);
        make.height.mas_equalTo(18);
    }];
    labUnder.textAlignment = NSTextAlignmentCenter;
    
    UIImageView *imgUnder = [UIImageView new];
    [self.view addSubview:imgUnder];
    [imgUnder mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(labUnder.mas_bottom).mas_offset(22);
        make.height.mas_equalTo(162);
        make.width.mas_equalTo(162);
        make.centerX.equalTo(self.view);
    }];
    
    [imgUnder sd_setImageWithURL:[NSURL URLWithString:self.faceInfo[@"killings"][@"stop"]]];
    
    UIImageView *imgUnderRight = [UIImageView new];
    [self.view addSubview:imgUnderRight];
    [imgUnderRight mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.width.mas_equalTo(66);
        make.bottom.equalTo(imgUnder);
        make.right.equalTo(imgUnder.mas_right).mas_offset(22);
    }];
    imgUnderRight.image = [UIImage imageNamed:@"face_pic_ok"];
    
    [self.view addSubview:self.apply];
    [_apply mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_offset(-bottomSafeHeight-5);
        make.left.mas_offset(24);
        make.right.mas_offset(-24);
        make.height.mas_equalTo(52);
    }];
    [_apply addTarget:self action:@selector(test) forControlEvents:UIControlEventTouchUpInside];
}


-(void)setupUI
{
    UIImageView *bgIV = [[UIImageView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:bgIV];
    
    [self.view addSubview:self.apply];
    [self.view bringSubviewToFront:_apply];
    [_apply mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_offset(-bottomSafeHeight-5);
        make.left.mas_offset(24);
        make.right.mas_offset(-24);
        make.height.mas_equalTo(52);
    }];
    
    UIImageView *icon = [UIImageView new];
    [self.view addSubview:icon];
    [icon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(98+64+MarginTop+20);
        make.left.mas_offset(13);
        make.right.mas_offset(-13);
        make.height.mas_equalTo(48);
    }];
    
    UIView *view = [UIView new];
    view.backgroundColor = MainColor;
    view.layer.cornerRadius = 20;
    [self.view addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(icon.mas_bottom).offset(10);
        make.left.mas_offset(13);
        make.right.mas_offset(-13);
        make.height.mas_equalTo(372);
    }];
    
    
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
//    [view addGestureRecognizer:tap];
//    [tap addActionBlock:^(id  _Nonnull sender) {
//        [self auth];
//    }];
    
    
    UIImageView *bg = [UIImageView new];
    bg.contentMode = UIViewContentModeScaleToFill;
    bg.image = [UIImage imageNamed:@"face_sbg"];
    [view addSubview:bg];
    [bg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_offset(0);
    }];
    
    UILabel *lab = [UILabel new];
    lab.textColor = HexColor(@"#212121");
    lab.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    [view addSubview:lab];
    [lab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(10);
        make.centerX.mas_equalTo(view);
    }];
    
    UIImageView *pimg = [UIImageView new];
    [view addSubview:pimg];
    [pimg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lab.mas_bottom).offset(13);
        make.centerX.mas_equalTo(view);
        make.height.mas_equalTo(144);
    }];
    
    UIImageView *pimgCenter = [UIImageView new];
    [pimg addSubview:pimgCenter];
    [pimgCenter mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(pimg);
        make.centerY.mas_equalTo(pimg);
        make.size.mas_equalTo(CGSizeMake(60, 60));
    }];
    pimgCenter.image = [UIImage imageNamed:@"face_pic_get"];
    
    
    UILabel *dlab = [UILabel new];
    dlab.numberOfLines = 2;
    dlab.textColor = HexColor(@"#212121");
    dlab.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    [view addSubview:dlab];
    [dlab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(pimg.mas_bottom).offset(20);
        make.left.mas_offset(23);
        make.right.mas_offset(-23);
    }];

    UIImageView *bottom = [UIImageView new];
    
    [view addSubview:bottom];
    [bottom mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_offset(-20);
        make.centerX.mas_equalTo(view);
        make.left.mas_offset(12);
        make.right.mas_offset(-12);
        make.top.equalTo(dlab.mas_bottom).offset(10);
        make.height.mas_equalTo(69);
    }];
    [_apply addTarget:self action:@selector(test) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    if(self.onControl == NO){
        bgIV.image = [UIImage imageNamed:@"face_bg1"];
        icon.image = [UIImage imageNamed:@"face_icon1"];
        lab.text = @"Front of ID photo";
        pimg.image = [UIImage imageNamed:@"face_pic1"];
        [pimg mas_updateConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(148, 148));
        }];
        pimgCenter.hidden = NO;
        dlab.text = @"Please submit certification according to the example to avoid blurring, obstruction, and reflection";
        bottom.image = [UIImage imageNamed:@"face_img1"];
    } else {
        if(self.backControl == NO){
            bgIV.image = [UIImage imageNamed:@"face_bg"];
            icon.image = [UIImage imageNamed:@"face_icon"];
            lab.text = @"Face recognition";
            pimg.image = [UIImage imageNamed:@"face_pic"];
            dlab.text = @"Please take a complete photo of yourself, avoiding blurring and not covering your face";
            bottom.image = [UIImage imageNamed:@"face_img"];
            pimgCenter.hidden = YES;
        }
    }
    [[LocationUpdata sharedInstance] startMarkTag];
}

-(void)test{
    
    if(self.onControl == NO){
        if(self.typeChos == YES || [self.type isEqualToString:@""]){
            self.typeChos = NO;
            FaceType *fv = [FaceType new];
            fv.typeA = self.faceInfo[@"voiceone"];
            fv.typeB = self.faceInfo[@"wellbred"];
            [self.navigationController pushViewController:fv animated:NO];
        } else {
            self.typeChos = YES;
            [[LocationUpdata sharedInstance] startMarkTag];
            [self auth];
        }
        
    } else if(self.backControl == NO){
        [self authCamera:@"2"];
    }
    else {
        [self.navigationController popViewControllerAnimated:NO];
    }
//    FaceDetail *vc = [FaceDetail new];
//    [self.navigationController pushViewController:vc animated:YES];
}
-(UIButton *)apply
{
    if (!_apply) {
        _apply = [UIButton buttonWithType:UIButtonTypeCustom];
        [_apply setImage:[UIImage imageNamed:@"auth_next"] forState:UIControlStateNormal];
    }
    return _apply;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)auth {
    UIAlertController *alert =  [UIAlertController alertControllerWithTitle: nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *camora = [UIAlertAction actionWithTitle:@"Camera" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self authCamera:@"1"];
        
    }];
    UIAlertAction *photo = [UIAlertAction actionWithTitle:@"Album Library" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self authPhoto];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:camora];
    [alert addAction:photo];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
}


- (void)authCamera:(NSString *)cam {
  
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
      if (granted) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self openCamera:cam];
        });
      } else {
          dispatch_async(dispatch_get_main_queue(), ^{
              UIAlertController *alert =  [UIAlertController alertControllerWithTitle: @"To facilitate your quick identity verification, we need to obtain the album permission for the avatar setting. Your information will only be used for this verification. We promise to strictly protect your privacy and security." message:nil preferredStyle:UIAlertControllerStyleAlert];
              UIAlertAction *ok = [UIAlertAction actionWithTitle:@"Setting" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                  [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:nil completionHandler:nil];
              }];
              UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
              [alert addAction:cancel];
              [alert addAction:ok];
              [self presentViewController:alert animated:YES completion:nil];
          });
      }
    }];
    
}

- (void)authPhoto {
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        if(status == PHAuthorizationStatusAuthorized){
            dispatch_async(dispatch_get_main_queue(), ^{
                [self openCameraLibrary];
                
            });
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                UIAlertController *alert =  [UIAlertController alertControllerWithTitle: @"To facilitate your quick identity verification, we need to obtain the album permission for the avatar setting. Your information will only be used for this verification. We promise to strictly protect your privacy and security." message:nil preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *ok = [UIAlertAction actionWithTitle:@"Setting" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:nil completionHandler:nil];
                }];
                UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
                [alert addAction:cancel];
                [alert addAction:ok];
                [self presentViewController:alert animated:YES completion:nil];
            });
        }
    }];
}

#pragma mark -CameraLib-
- (void)openCameraLibrary {
    self.photoType = @"2";
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:imagePicker animated:YES completion:nil];
}

- (void)openCamera:(NSString *)cam {
    self.photoType = @"1";
    UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.editing = NO;
    imagePicker.delegate = self;
//    imagePicker.allowsEditing = YES;
    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
    if([cam isEqualToString:@"1"]){
        imagePicker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
    } else {
        imagePicker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
    }
    
    [self presentViewController:imagePicker animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<UIImagePickerControllerInfoKey, id> *)editingInfo API_DEPRECATED("", ios(2.0, 3.0)) {
    
    if (image) {
        if(!self.onControl){
            [DataFrameMove frameMoverImage:image ForPost:@"/cham/kittys" MoverPost:YES frameParm:@{@"egypt":self.photoType,@"herin":@"11",@"hesnortedand":self.type} finish:^(id  _Nonnull info) {
       
                self.peso = info;
                [self infoEdit:self.peso];
            }];
        } else {
            
//            UIImage *im = [UIImage imageNamed:@"fpic"];
            [DataFrameMove frameMoverImage:image ForPost:@"/cham/kittys" MoverPost:YES frameParm:@{@"egypt":self.photoType,@"herin":@"10",@"hesnortedand":@""} finish:^(id  _Nonnull info) {
                [self startMark:@"4"];
                [self moveReq];
            }];
        }
        
    }
    [picker dismissViewControllerAnimated:NO completion:^{
        
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:NO completion:^{
        
    }];
}


- (void)infoEdit:(NSDictionary *)dict {
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    InfoVerify *ivy = [[InfoVerify alloc]initWithFrame:CGRectZero];
    [view addSubview:ivy];
    ivy.fullName.text = dict[@"fashion"][@"madnevertheless"] ? dict[@"fashion"][@"madnevertheless"] : @"";
    ivy.idNo.text = dict[@"fashion"][@"chuhou"] ? dict[@"fashion"][@"chuhou"] : @"";
    NSString *birth = dict[@"fashion"][@"pleasuresuch"] ? dict[@"fashion"][@"pleasuresuch"] : @"";
    NSArray *birs = [birth componentsSeparatedByString:@"-"];
    if(birs.count > 1){
        birth = [NSString stringWithFormat:@"%@-%@-%@",birs[0],birs[1],birs[2]];
        [[NSUserDefaults standardUserDefaults] setObject:birth forKey:@"birth"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
    ivy.birthday.text = birth;
    [ivy mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(view);
        make.left.mas_offset(28);
        make.right.mas_offset(-28);
        make.height.mas_equalTo(500);
    }];
    ivy.closeAction = ^{
        [view removeFromSuperview];
    };
    ivy.commitAction = ^(NSString * _Nonnull str1, NSString * _Nonnull str2, NSString * _Nonnull str3) {
        
        NSLog(@"%@-%@-%@",str1,str2,str3);
        [DataFrameMove frameMoverForPost:@"/cham/clothing" MoverPost:YES frameParm:@{@"herin":@"11",@"hesnortedand":self.type,@"pleasuresuch":str3,@"madnevertheless":str1,@"chuhou":str2} finish:^(id  _Nonnull info) {
            [view removeFromSuperview];
            [self startMark:@"3"];
            [self moveReq];
        }];
    };
    [self.view addSubview:view];
    [self.view bringSubviewToFront:view];
}
@end
